package com.yoshino.leetcode.oneHundred.fifteenth;

import java.util.ArrayList;
import java.util.List;

class Solution {

    public static List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        // 中序遍历
        res = new ArrayList<>();
        bfs(root, target, new ArrayList<>());
        return res;
    }

    private void bfs(TreeNode root, int target, List<Integer> temp) {
        if (root == null) {
            return;
        }
        if (root.val == target) {
            temp.add(root.val);
            if (root.left == null && root.right == null) {
                res.add(new ArrayList<>(temp));
            } else {
                bfs(root.left, target - root.val, temp);
                bfs(root.right, target - root.val, temp);
            }
        } else {
            temp.add(root.val);
            bfs(root.left, target - root.val, temp);
            bfs(root.right, target - root.val, temp);
        }
        temp.remove(temp.size() - 1);
    }

    Node pre, head;
    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        dfs(root);
        pre.right = head;
        head.left = pre;
        return head;
    }

    private void dfs(Node cur) {
        // 递归结束
        if (cur == null) {
            return;
        }
        dfs(cur.left);
        // 判断是否为第一个节点
        if (pre == null) {
            head = cur;
        } else {
            pre.right = cur;
        }
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    }

    private int count = 0, ans= 0;
    public int kthLargest(TreeNode root, int k) {
        dfs(root, k);
        return ans;
    }

    private void dfs(TreeNode cur, int k) {
        // 递归结束
        if (cur.right != null) {
            dfs(cur.right, k);
        }
        if (++count == k) {
            ans = cur.val;
            return;
        }
        if (cur.left != null) {
            dfs(cur.left, k);
        }
    }
}